package com.company.tree;

import com.company.TreeNode;
import sun.reflect.generics.tree.Tree;

import java.time.Year;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * @author jrue
 * @version 1.0
 * @date 2020/1/27 10:12
 * https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
 * 给定一个二叉树，找出其最大深度。
 * 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
 * 说明: 叶子节点是指没有子节点的节点。
 */
public class MaximumDepthOfBinaryTree {

    public void traversalWithStack(TreeNode root) {
        if (root == null) return;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode thisNode = stack.pop();
            System.out.print(thisNode.val + " ");
            if (thisNode.right != null) {
                stack.push(thisNode.right);
            }
            if (thisNode.left != null) {
                stack.push(thisNode.left);
            }
        }
    }

    public void traversal(TreeNode root) {

        if (root == null) return;
        traversal(root.left);
        System.out.print(root.val + " ");
        traversal(root.right);

    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);

        new MaximumDepthOfBinaryTree().traversal(root);
        System.out.println();
        new MaximumDepthOfBinaryTree().traversalWithStack(root);
        System.out.println();
        System.out.println(new MaximumDepthOfBinaryTree().maxDepth(root));
    }

    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<>();

        int preNodeCount = 1;
        int thisNodeCount = 0;
        queue.add(root);
        int res = 0;
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            preNodeCount--;

            if (node.left != null) {
                thisNodeCount++;
                queue.offer(node.left);
            }
            if (node.right != null) {
                thisNodeCount++;
                queue.offer(node.right);
            }

            if (preNodeCount == 0) {
                res++;
                preNodeCount = thisNodeCount;
                thisNodeCount = 0;
            }
        }

        return res;
    }
}
